package com.leetcode.partition6;

import com.leetcode.common.TreeNode;

/**
 * @author `RKC`
 * @date 2021/11/18 9:04
 */
public class LC563二叉树的坡度 {

    private static int answer = 0;

    public static int findTilt(TreeNode root) {
        postorder(root);
        return answer;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(4, new TreeNode(2, new TreeNode(3), new TreeNode(5)),
                new TreeNode(9, null, new TreeNode(7)));
        System.out.println(findTilt(root));
    }

    private static int postorder(TreeNode root) {
        if (root == null) return 0;
        int left = postorder(root.left), right = postorder(root.right);
        answer += Math.abs(left - right);
        return root.val + left + right;
    }
}
